package com.xiaojie.importdata.handler.impl;

import com.xiaojie.context.DataInfoContext;
import com.xiaojie.importdata.handler.AbstractReplaceFieldValueHandler;
import com.xiaojie.parse.model.Table;
import com.xiaojie.toolkits.FieldNameUtil;

import java.util.Map;
import java.util.Optional;

/**
 * 替换表内相互依赖字段
 *
 * @ClassName ReplaceSelfRefFieldVale
 * @Author wangye
 * @Date 2022/3/13
 **/
public class ReplaceSelfRefFieldVale extends AbstractReplaceFieldValueHandler {


    /**
     * 替换字段依赖本表字段的新值
     * 从[当前表]中[被关联字段]根据[旧值]获取对应的[新值]
     * 查找到的新值为null则不替换
     * 不支持字段多层次依赖 A->B,B->C，值不会被替换
     * 不支字段持循环依赖 A->B B->C C->A 值不会被替换
     *
     * @param tableName
     * @param table
     * @param rowData
     * @Author: wangye
     * @Date: 2022/2/23 10:20
     * @return:
     **/
    @Override
    public void replaceFieldValue(String tableName, Table table, Map rowData) {

        Map<String, Map<String, Map>> refFieldValueMap = DataInfoContext.get().getRefFieldValueMap();
        Map<String, String> selfRelFieldMap = table.getSelfRelFields();
        for (Map.Entry<String, String> entry : selfRelFieldMap.entrySet()) {
            String fieldName = FieldNameUtil.convert(entry.getKey());
            Object fieldValue = rowData.get(fieldName);
            //被关联字段名名称
            String refedFieldName = FieldNameUtil.convert(entry.getValue());
            //从[当前表]中[被关联字段]根据[旧值]获取对应的[新值],如果获取的值为null则newFieldVlaue的值为原始值
            Object newFieldValue = Optional.ofNullable(refFieldValueMap.get(tableName))
                    .flatMap(m -> Optional.ofNullable(m.get(refedFieldName)))
                    .flatMap(m -> Optional.ofNullable(m.get(fieldValue)))
                    .orElse(fieldValue);
            rowData.put(fieldName, newFieldValue != null ? newFieldValue : fieldValue);
        }
    }

    private static class HOLDER {
        private static ReplaceSelfRefFieldVale instance = new ReplaceSelfRefFieldVale();
    }

    public static ReplaceSelfRefFieldVale getInstance() {
        return HOLDER.instance;
    }

    private ReplaceSelfRefFieldVale() {
    }


}
